package com.wedimob.slideshare.source;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.wedimob.slideshare.SearchCriteria;
import com.wedimob.slideshare.SortBy;

public class YoutubeStrategy implements SourceStrategy {

    //@TODO("https://gdata.youtube.com/feeds/api/videos?q=football+-soccer&orderby=published&start-index=11&max-results=10&v=2?alt=json")
    public final static String URL_BASE = "http://www.youtube.com";
    public final static String SEARCH_PATTERN = URL_BASE + "/results?search_query";
    public final static String VIDEO_PAGE_PATTERN = URL_BASE + "/watch?v=";
    private final static double NB_ITEM_PER_PAGE = 25.0;
    
    @Override
    public String getUrlBase() {
        return URL_BASE;
    }

    @Override
    public List<URL> generateUrl(SearchCriteria criteria) {
        try {
            List<URL> result = new ArrayList<URL>();
            int nbPages = Source.getNbPages(criteria.getLimit(), NB_ITEM_PER_PAGE);
            int begin = (int) Math.floor(criteria.getBegin() / NB_ITEM_PER_PAGE);
            for (int i = begin; i < begin + nbPages; i++) {
                result.add(
                        new URL(URL_BASE
                                + "/results?search_query=" + criteria.getKeyword().replaceAll(" ", "+")
                                + "&filters=video&page=" + (i + 1)
                                + "&search_sort=" + convert(criteria.getSortBy())));
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String convert(SortBy sortBy) {
        switch (sortBy) {
        case RELEVANCE:
            return "";
        case LAST_PUBLICATION:
            return "video_date_uploaded";
        case POPULARITY:
            return "video_view_count";
        }
        return null;
    }

}
